cmake_minimum_required(VERSION 3.10)

# 确保 FLUTTER_ROOT 环境变量已设置
if(NOT DEFINED ENV{FLUTTER_ROOT})
    message(FATAL_ERROR "错误: FLUTTER_ROOT 环境变量未设置。请先运行 'source envsetup' 设置环境变量。")
endif()

# 设置 smarthome 项目路径
set(SMARTHOME_DIR ${CMAKE_CURRENT_SOURCE_DIR}/smarthome)

# 检查 smarthome 目录是否存在
if(NOT EXISTS ${SMARTHOME_DIR})
    message(FATAL_ERROR "错误: smarthome 目录不存在: ${SMARTHOME_DIR}")
endif()

# 将Flutter构建目录添加到清理文件列表
set_property(
    DIRECTORY
    APPEND PROPERTY
    ADDITIONAL_MAKE_CLEAN_FILES
    "${SMARTHOME_DIR}/build"
)

# 创建一个自定义目标，用于清理Flutter项目
add_custom_target(flutter-clean
    COMMAND ${CMAKE_COMMAND} -E echo "清理 Flutter web 项目..."
    COMMAND cd ${SMARTHOME_DIR} && $ENV{FLUTTER_ROOT}/bin/flutter clean
    COMMENT "清理 Flutter web 应用 - smarthome"
    VERBATIM
)

# 创建一个组合目标，它会执行标准的clean和我们的flutter-clean
add_custom_target(clean-all
    COMMAND ${CMAKE_COMMAND} --build . --target clean
    COMMAND ${CMAKE_COMMAND} --build . --target flutter-clean
    COMMENT "执行完整清理（包括Flutter项目）"
    VERBATIM
)

# 创建构建 Flutter web 项目的自定义目标
add_custom_target(smarthome_web
    COMMAND ${CMAKE_COMMAND} -E echo "构建 Flutter web 项目..."
    COMMAND cd ${SMARTHOME_DIR} && $ENV{FLUTTER_ROOT}/bin/flutter pub get
    COMMAND cd ${SMARTHOME_DIR} && $ENV{FLUTTER_ROOT}/bin/flutter build web --release
    COMMENT "构建 Flutter web 应用 - smarthome"
    VERBATIM
)

# 安装 web 构建输出到 bin/nginx 目录
install(
    DIRECTORY ${SMARTHOME_DIR}/build/web
    DESTINATION ${CMAKE_INSTALL_PREFIX}/bin/nginxd/
    COMPONENT smarthome
    PATTERN "*.md" EXCLUDE
    PATTERN "*.log" EXCLUDE
    PATTERN ".git*" EXCLUDE
)

# 添加安装消息
install(CODE "message(STATUS \"已安装 smarthome web 应用到 \${CMAKE_INSTALL_PREFIX}/bin/nginx\")")